<?php

namespace App\Console\Commands;

use App\Models\DistrictModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class UpdateDistrict extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:update-district';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->alert("更新省市区信息");
        $this->truncate();
        $this->alert("开始更新");
        $district = $this->getDistrict();
        $this->storage($district);
        $this->line('更新完毕');
    }
    private function truncate()
    {
        $this->alert("删除旧数据");
        DistrictModel::query()->truncate();
        $this->alert("旧数据删除完成");
    }
    private function storage( $data, int $pid = 0)
    {
        foreach ($data as $item) {
            $array = [
                'citycode' => empty($item['citycode'])?0:$item['citycode'],
                'adcode' => $item['adcode'],
                'name' => $item['name'],
                'level' => $this->getLevel($item['level']),
                'pid' => $pid,
            ];
            if ($array) {
                $res = DistrictModel::query()->create($array);
                //继续处理下级数据
                if ($item['districts']) {
                    $this->storage($item['districts'], $res->id);
                }
            }

        }
    }

    private function getDistrict()
    {

        $url = 'https://restapi.amap.com/v3/config/district';
        $data = [
            'key' => $this->getKey(),
            'subdistrict' => 3
        ];
        $res = Http::get($url, $data);
        return $res->json()['districts'][0]['districts'];
    }

    private function getLevel(string $level): int
    {
        return [
            'province' => 1,
            'city' => 2,
            'district' => 3,
        ][$level] ?? 0;
    }

    private function getKey(): string
    {
        return env('GAODE_KEY');
    }
}
